package com.gitee.kamismile.stoneComEx.util.excel;

import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import com.gitee.kamismile.stoneComEx.util.view.ExcelBean;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CSVFileUtil {
    private CSVFileUtil() {
    }

    public static void exportData(ExcelBean excelBean, String filePath, boolean append) {
        BufferedWriter fout = null;

        // 保存Excel文件到服务器上

        CSVPrinter printer = null;
        try {
            // 判断目录是否存在，不存在则创建目录
            File file = new File(filePath).getParentFile();
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(filePath, append);
            if (!append) {
                fileOutputStream.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            }
            fout = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "UTF-8"), 1024);

            List<String[][]> colmons = excelBean.getMuchColmons();
            List<List<Map<String, Object>>> maps = excelBean.getMaps();
            for (int cols = 0; cols < colmons.size(); cols++) {
                String[] fileHeader = new String[colmons.get(cols).length];
                for (int i = 0; i < colmons.get(cols).length; i++) {
                    fileHeader[i] = colmons.get(cols)[i][1];
                }
                CSVFormat format = CSVFormat.DEFAULT
                        .withQuoteMode(QuoteMode.ALL_NON_NULL);
                if (!append) {
                    format=format.withHeader(fileHeader);
                }

                printer = new CSVPrinter(fout, format);


                for (int i = 0; i < maps.get(cols).size(); i++) {
                    List<String> records = new ArrayList<>();
                    for (int j = 0; j < colmons.get(cols).length; j++) {
                        records.add(StringEscapeUtils.escapeCsv(ValueUtils.isStringNull(
                                maps.get(cols).get(i).get(colmons.get(cols)[j][0]), "")));
                    }
                    printer.printRecord(records);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ValueUtils.isNotNull(fout)) {
                IOUtils.closeQuietly(fout);
            }

            if (ValueUtils.isNotNull(printer)) {
                IOUtils.closeQuietly(printer);
            }
        }
    }

    public static void exportData(ExcelBean excelBean, String filePath) {
        exportData(excelBean, filePath, false);
    }

}
